%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% File:               marginal.m
%
% Authors:            Sergio Ascencio and Miguel Rueda
%
% Description:        It computes predicted best responses and standard
%                     errors
% Language:           MATLAB R2013b (8.2.0.701) 64 Bit

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


function [UCI,LCI,pred]=marginal(beta,betas_monte,mean_X_PRI,mean_X_PAN,pri_pan,m_h)

%saving the simulated predictions
preds=cell(2,size(betas_monte,2));
for i=1:size(betas_monte,2)
    [p_PAN,p_PRI]=predicted_probs(betas_monte(:,i),mean_X_PRI,mean_X_PAN);
    if pri_pan==1
        preds{1,i}=p_PRI(:,2);
        preds{2,i}=p_PRI(:,3);
    else
        preds{1,i}=p_PAN(:,2);
        preds{2,i}=p_PAN(:,3);
    end    
end

%main prediction
[p_PAN,p_PRI]=predicted_probs(beta,mean_X_PRI,mean_X_PAN);
if pri_pan==1
   pred_m=p_PRI(:,2);
   pred_h=p_PRI(:,3);
else
   pred_m=p_PAN(:,2);
   pred_h=p_PAN(:,3);
end  

%choosing between probability of medium or high
if m_h==1
    preds=cell2mat(preds(1,:));
    pred=pred_m;
else
    preds=cell2mat(preds(2,:));
    pred=pred_h;
end

%calculating confidence intervals
s_e=std(preds,0,2);
LCI=pred+(norminv((1-0.95)/2,0,1))*s_e;
UCI=pred-(norminv((1-0.95)/2,0,1))*s_e;

end

